package bin_tree.NewCoder;

import java.util.Scanner;

/**
 * @author shkstart
 * 根据先序遍历结果还原二叉树，输出中序便利店结果
 * @create 2022-10-23-17:53
 */
public class KY11 {
    private static class TreeNode {
        char val;
        TreeNode left;
        TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        获取用户的多组输入
        while (scanner.hasNext()) {
//            字符串形式的先序二叉树结果
            String line = scanner.next();
//            将str字符串组成二叉树形式
            TreeNode root = build(line);
//            中序遍历二叉树，按照格式打印节点值
            inOrder(root);
//            每个结果换一行
            System.out.println();
        }

    }

    //    中序遍历
    private static void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);

    }

    //    根据先序遍历结果将字符串还原二叉树，返回二叉树的根节点
    private static TreeNode build(String line) {
        return preOrderBuild(line);
    }

    //    a b c # # d e # g # # f # # #
//    str->char
    static int index = 0;

    private static TreeNode preOrderBuild(String line) {

//        取得当前需要处理的字符 char-->TreeNode
        char c = line.charAt(index);
        if (c == '#') {
            return null;
        }
//        根节点
        TreeNode root = new TreeNode(c);
//        继续处理下一个字符
        index++;
        root.left = preOrderBuild(line);
        index++;
        root.right = preOrderBuild(line);
        return root;
    }

}
